data "alicloud_instance_types" "instance_type" {
  instance_type_family = var.instance_type_family
  cpu_core_count       = var.cpu_core_count
  memory_size          = var.memory_size
}

data "alicloud_zones" "ecs" {
  available_resource_creation = "VSwitch"
  available_instance_type     = data.alicloud_instance_types.instance_type.instance_types[0].id
}

module "ecs_cluster" {
  source  = "alibaba/ecs-instance/alicloud"
  version = "2.8.0"

  number_of_instances         = var.number_of_instances

  vswitch_id                  = var.vswitch_id != "" ? var.vswitch_id : var.exist_vswitch_ids[index(var.exist_azs, data.alicloud_zones.ecs.zones[0].id)]
  instance_type               = var.instance_type != "" ? var.instance_type : data.alicloud_instance_types.instance_type.instance_types[0].id

  name                        = var.name
  host_name                   = var.host_name
  use_num_suffix              = var.use_num_suffix
  image_id                    = var.image_id
  security_group_ids          = var.security_groups
  associate_public_ip_address = var.associate_public_ip_address
  internet_max_bandwidth_out  = var.internet_max_bandwidth_out
  key_name                    = var.key_name
  user_data                   = var.user_data

  system_disk_category        = var.system_disk_category
  system_disk_size            = var.system_disk_size

  tags = {
    Created      = "Terraform"
    Environment = "dev"
  }
}

resource "null_resource" "setup_db" {
  count = var.setup_db ? 1 : 0

  connection {
    type        = "ssh"
    user        = "root"
    private_key = var.private_key
    host        = module.ecs_cluster.this_public_ip[0]
  }
  provisioner "file" {
    content     = var.content
    destination = "/root/setup.sql"
  }
  depends_on = [module.ecs_cluster]
}

resource "null_resource" "exec" {
  count = var.setup_db ? 1 : 0

  triggers = {
    cluster_instance_ids = join(",", var.triggers)
  }
  connection {
    type        = "ssh"
    user        = "root"
    private_key = var.private_key
    host        = module.ecs_cluster.this_public_ip[0]
  }
  provisioner "remote-exec" {
    inline = [
      "mysql -u ${var.rds_username} -p${var.rds_passpwrd} -h ${var.rds_connection_string} -P ${var.rds_port} pipeline < /root/setup.sql"
    ]
  }
  depends_on = [
    module.ecs_cluster,
    null_resource.setup_db
  ]
}

resource "null_resource" "init" {
  connection {
    type        = "ssh"
    user        = "root"
    private_key = var.private_key
    host        = module.ecs_cluster.this_public_ip[0]
  }
  provisioner "remote-exec" {
    script = "${path.module}/init.sh"
  }
  depends_on = [module.ecs_cluster]
}